﻿using System;
using System.Text.RegularExpressions;
using ValidationEngine.Commons;
using ValidationEngine.Commons.Enums;
using ValidationEngine.Commons.Interfaces;
using ValidationEngine.Tools;

namespace ValidationEngine.ValidationRules
{
    public class RegExpRule : BaseValidationRule
    {
        #region Members
        private readonly string _pattern;
        private readonly Regex _regex; 
        #endregion

        protected override IValidationInfo ApplyRule(IValidationContext ctx)
        {
            var modelValue = ModelHelper.GetPropertyValue<string>(ctx);
            if (null == modelValue)
            {
                return Result;
            }

            DefResult = _regex.Match(modelValue, 0).Length != modelValue.Length ? _defErrorMsg : null;

            return Result;
        }

        #region Ctor
        public RegExpRule(
          string pattern,
          string defErrorText = null,
          RuleApplingContext applyCtx = RuleApplingContext.Always,
          ValidationErrorType errorType = ValidationErrorType.Error)
        {
            this._pattern = pattern;
            this._regex = new Regex(pattern, RegexOptions.IgnoreCase);
            this.ApplingContext = applyCtx;
            this._defErrorType = errorType;
            this._defErrorMsg = defErrorText ?? String.Format("Value should match expression: ({0})", _pattern);
        } 
        #endregion
    }
}
